package com.sxy.web; /**
 * @author 宋鑫宇
 * @version 1.0
 */

import com.sxy.pojo.User;
import com.sxy.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    //创建service层对象
    private UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建session
        HttpSession session = request.getSession();
        //1.接收前端发送的信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //获取复选框数据
        String remember = request.getParameter("remember");
        //2.调用service层方法执行
        User user = userService.select(username, password);
        //3.判断用户是否存在
        if (user == null){
            request.setAttribute("msg","用户名或密码错误!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }
        if ("1".equals(remember)){
            //勾选复选框，发送cookie
            //创建cookie
            Cookie c_username = new Cookie("username", username);
            Cookie c_password = new Cookie("password", password);
            //设置cookie的存活时间为1小时
            c_username.setMaxAge(60*60);
            c_password.setMaxAge(60*60);
            //发送cookie
            response.addCookie(c_username);
            response.addCookie(c_password);
        }
        //将用户名存到session中
        session.setAttribute("user",user);
        //登陆成功，重定向到查询所有目录
        response.sendRedirect("/selectAllServlet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
